package com.example.myapplicationfinalwork.ui.weather;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.example.myapplicationfinalwork.MainActivity;
import com.example.myapplicationfinalwork.R;
import com.example.myapplicationfinalwork.common.Analysis;
import com.example.myapplicationfinalwork.common.Weather;
import com.example.myapplicationfinalwork.common.WeatherDesc;
import com.example.myapplicationfinalwork.controller.OkHttpController;
import com.example.myapplicationfinalwork.databinding.WeatherTodayFragmentBinding;
import com.example.myapplicationfinalwork.model.MapViewModel;
import com.example.myapplicationfinalwork.model.WeatherTodayViewModel;
import com.example.myapplicationfinalwork.util.WeatherChartView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class WeatherTodayFragment extends Fragment {
    final String TAG="weatherFragment";
    private WeatherTodayViewModel mViewModel;
    private MapViewModel mapViewModel;
    private WeatherTodayFragmentBinding binding;
    private List<WeatherDesc> listDesc =new ArrayList<>();
    private List<Weather> listForecast=new ArrayList<>();
    private String yesterday_high="15",yesterday_low="-8";
    private Gson gson=new Gson();
    public Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                Bundle bundle=msg.getData();
                mViewModel.setNowTem(bundle.getString("nowTem")+"℃");

                JSONObject data=(JSONObject) msg.obj;
                try {
                    JSONArray forecast=data.getJSONArray("forecast");
                    for(int i=0;i<forecast.length();++i){
                        Weather tmp=gson.fromJson(forecast.getJSONObject(i).toString(),Weather.class);
                        listForecast.add(tmp);
                    }

                    JSONObject yesterday=data.getJSONObject("yesterday");
                    yesterday_high=yesterday.getString("high");
                    yesterday_low=yesterday.getString("low");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Weather today=listForecast.get(0);
                mViewModel.setTem(Analysis.calTemperature(today.getHigh())+" / "+Analysis.calTemperature(today.getLow()));
                mViewModel.setWind(today.getFengxiang()+"  "+ Analysis.calFengli(today.getFengli()));
                mViewModel.setType(today.getType());
                mViewModel.setListForecast(listForecast);
            }
            else if(msg.what==2){
                Bundle bundle=msg.getData();
                String nowTem=bundle.getString("nowTem");
                Weather today=(Weather) msg.obj;

                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
                View view = View.inflate(getContext(), R.layout.model_box_weather_today, null);

                TextView model_cityname=view.findViewById(R.id.model_cityname),
                        model_nowTem=view.findViewById(R.id.model_nowTem),
                        model_tem=view.findViewById(R.id.model_tem),
                        model_wind=view.findViewById(R.id.model_wind),
                        model_type=view.findViewById(R.id.model_type);

                model_cityname.setText(bundle.getString("cityname"));
                model_nowTem.setText(bundle.getString("nowTem")+"℃");
                model_tem.setText(Analysis.calTemperature(today.getHigh())+" / "+Analysis.calTemperature(today.getLow()));
                model_wind.setText(today.getFengxiang()+"  "+ Analysis.calFengli(today.getFengli()));
                model_type.setText(today.getType());


                alertDialog
                        .setTitle("详情")
                        .setIcon(R.drawable.ic_model_desc)
                        .setView(view)
                        .create();
                alertDialog.show();
            }
            else if(msg.what==3){
                Bundle bundle=msg.getData();
                Weather today=(Weather) msg.obj;
                listDesc.add(new WeatherDesc(bundle.getString("cityname"),bundle.getString("nowTem")+"℃",today.getType()));
                initRecycleViewToday();
            }
        }
    };
    private OkHttpController okHttpController=new OkHttpController(handler);

    public static WeatherTodayFragment newInstance() {
        return new WeatherTodayFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding=WeatherTodayFragmentBinding.inflate(inflater,container,false);
        mapViewModel = new ViewModelProvider(getActivity(),new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);
        mViewModel = new ViewModelProvider(this).get(WeatherTodayViewModel.class);

        initImg();
        modelUpdate();

        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        // TODO: Use the ViewModel
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    void initImg(){
        Log.i("myDebug", "initImg: ");
        Glide.with(getActivity())
                .load("https://bing.ioliu.cn/v1/rand?w=1280&h=768")
                .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                .fitCenter()
                .into(binding.imgWeatherTodayCity);
    }

    void initRecycleViewToday(){
        RecyclerView rv=binding.rvWeatherToday;
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(layoutManager);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        MyAdapter myAdapter=new MyAdapter();
        rv.setAdapter(myAdapter);
    }

    void initForecastChart(){
        WeatherChartView chartView = binding.weatherForecastChart;
        List<Integer> highList=new ArrayList<>(),
                lowList=new ArrayList<>();

        for(Weather weather: listForecast){
            highList.add(Analysis.getNumOfTemperature(weather.getHigh()));
            lowList.add(Analysis.getNumOfTemperature(weather.getLow()));
        }
        int[] high=new int[highList.size()+1];
        int[] low=new int[lowList.size()+1];
        for(int i=0;i<highList.size();++i){
            high[i+1]=highList.get(i);
        }
        for(int i=0;i<lowList.size();++i){
            low[i+1]=lowList.get(i);
        }
        high[0]=Analysis.getNumOfTemperature(yesterday_high);
        low[0]=Analysis.getNumOfTemperature(yesterday_low);
        chartView.setTempDay(high);
        chartView.setTempNight(low);
        chartView.invalidate();
    }

    private void modelUpdate(){
        mapViewModel.getCity(((MainActivity)getActivity()).localedCity).observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String city) {
                binding.tvWeatherTodayCity.setText(city);
                okHttpController.getWeather(city,"");
            }
        });

        mViewModel.getNowTem().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.weatherTodayNowTem.setText(s);
            }
        });

        mViewModel.getTem().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.weatherTodayTem.setText(s);
            }
        });

        mViewModel.getWind().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.weatherTodayWind.setText(s);
            }
        });

        mViewModel.getType().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.weatherTodayType.setText(s);
            }
        });

        mViewModel.getListForecast().observe(getViewLifecycleOwner(), new Observer<List<Weather>>() {
            @Override
            public void onChanged(List<Weather> strings) {
                listForecast=strings;
                initForecastChart();
            }
        });

        mViewModel.getListCity(((MainActivity)getActivity()).username).observe(getViewLifecycleOwner(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> strings) {
                listDesc.clear();
                for(String city:strings){
                    /*if(city.equals(((MainActivity)getActivity()).localedCity))
                        continue;*/
                    okHttpController.getWeatherList(city,3);
                }
            }
        });


    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHoder> {

        @NonNull
        @Override
        public MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //View view = View.inflate(getContext(), R.layout.rv_desc_list, null);
            View view =  LayoutInflater.from(getContext()).inflate(R.layout.rv_desc_list, parent, false);
            MyViewHoder myViewHoder = new MyViewHoder(view);
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHoder holder, int position) {
            WeatherDesc desc= listDesc.get(position);
            holder.mCity.setText(desc.city);
            holder.mTem.setText(desc.tem);
            holder.mType.setText(desc.type);
            holder.mPane.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    okHttpController.getWeatherList(holder.mCity.getText().toString(),2);
                }
            });

        }

        @Override
        public int getItemCount() {
            return listDesc.size();
        }
    }

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mCity,mTem,mType;
        LinearLayout mPane;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mCity=itemView.findViewById(R.id.listDesc_city);
            mTem=itemView.findViewById(R.id.listDesc_tem);
            mType=itemView.findViewById(R.id.listDesc_type);
            mPane=itemView.findViewById(R.id.listDesc_pane);
        }
    }
}